import gtk, os
from GMM import utils

class frame(gtk.EventBox):
    def __init__(self, string, projectfolder):
        gtk.EventBox.__init__(self)
        
        self.len=5
        self.len_effect=1
        self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#BBBBBB"))
        self.trans_effect="none"
        
        self.projectfolder=projectfolder
        
        data=string.split("#")
        photo=data[0]
        print "loading", photo
        if len(data)>1: 
            try: self.len=int(data[1])
            except: print "data error, expect int:", data[1]
        if len(data)>2: self.trans_effect=data[2]
        if len(data)>3: 
            try: self.len_effect=int(data[3])
            except: print "data error, expect int:", data[3]
        
        
        self.photo=""
        self.thumbnail=""
        label=gtk.Label(utils.get_name(photo))
        label.show()
        
        VBox=gtk.VBox()
        VBox.pack_end(label, False, False)
        
        image=gtk.Image()
        self.pixbuf = ""
        self.set_picture(photo)
        
        width=self.pixbuf.get_width()
        height=self.pixbuf.get_height()
        
        if width > 100:
                height=height*100/width
                width=100
                if height > 48:
                    width=width*48/height
                    height=48
        pixbuf = self.pixbuf.scale_simple(width, height, gtk.gdk.INTERP_HYPER)
        
        image.set_from_pixbuf(pixbuf)
        VBox.pack_start(image)
        
        self.set_tooltip_text(photo)
        self.add(VBox)
        self.show_all()

    def set_len(self, lenght):
        self.len=lenght
    
    def set_width(self, width):
        self.set_size_request(width, 48)
        pass
    
    def get_frame(self):
        return self.photo, self.len
    
    def set_picture(self, photo):
        try:
            os.mkdir(self.projectfolder + "photos/")
        except: pass
        photo_name=utils.get_name_no_ext(photo)
        self.photo=self.projectfolder + "photos/" + photo_name + ".png"
        if (os.path.isfile(self.photo)==False):
            utils.execute(["cp", photo, self.photo])
        
        self.make_thumb()
    
    def make_thumb(self):
        try:
            os.mkdir(self.projectfolder + "thumb/")
        except: pass
        photo_name=utils.get_name_no_ext(self.photo)
        self.thumbnail=self.projectfolder + "thumb/"+photo_name+".png"
        if os.path.isfile(self.thumbnail)==False:
            utils.execute(["convert", self.photo, "-resize", "200x200 ", self.thumbnail])
        
        self.pixbuf=gtk.gdk.pixbuf_new_from_file(self.thumbnail)
    
    def to_string(self):
        return self.photo + "#" + str(self.len) + "#" + self.trans_effect + "#" + str(self.len_effect)